<template>
  <div class="chat-container">
    <!-- 角色选择区域 -->
    <div class="role-selector">
      <van-radio-group v-model="selectedRole" direction="horizontal" @change="onRoleChange">
        <van-radio name="医生">医生</van-radio>
        <van-radio name="厨师">厨师</van-radio>
        <van-radio name="老师">老师</van-radio>
        <van-radio name="律师">律师</van-radio>
        <van-radio name="女朋友">女朋友</van-radio>
        <van-radio name="狗">狗</van-radio>
        <van-radio name="custom">自定义</van-radio>
      </van-radio-group>
    </div>

    <!-- 自定义角色输入 -->
    <div v-if="selectedRole === 'custom'" class="custom-role-form">
      <van-field v-model="customRoleName" placeholder="请输入角色名称"/>
      <van-field v-model="customRoleDesc" placeholder="请输入角色描述"/>
      <van-button size="small" type="primary" @click="saveCustomRole">保存角色</van-button>
    </div>

    <!-- 聊天消息区域 -->
    <div ref="messagesContainer" class="chat-messages">
      <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
        <div class="message-content">{{ msg.content }}</div>
      </div>
      <div v-if="isLoading" class="message assistant">
        <div class="message-content">{{ partialResponse }}<span class="cursor">|</span></div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <van-field
          v-model="inputMessage"
          :disabled="isLoading"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
      />
      <van-button
          :disabled="!inputMessage.trim()"
          :loading="isLoading"
          type="primary"
          @click="sendMessage"
      >
        发送
      </van-button>
    </div>
  </div>
</template>

<script setup>
import {computed, nextTick, onUnmounted, ref, watch} from 'vue'
import {showFailToast, showToast} from 'vant'
import {_axios} from '../api/index.js'

// 响应式数据
const selectedRole = ref('医生')
const customRoleName = ref('')
const customRoleDesc = ref('')
const inputMessage = ref('')
const messages = ref([])
const isLoading = ref(false)
const partialResponse = ref('')
const abortController = ref(null)
const messagesContainer = ref(null)

// 欢迎消息映射
const welcomeMessages = {
  '医生': '你好！我是一名专业医生，有什么健康问题可以问我。请注意，线上咨询不能替代面诊，严重情况请及时就医。',
  '老师': '你好呀！我是你的老师，有什么学习上的问题或者想了解的知识，都可以跟我说哦。',
  '厨师': '你好！我是一名厨师，无论是想学习新菜式，还是需要食材搭配建议，都可以问我。',
  '律师': '你好，我是律师。如果你有法律相关问题，可以向我咨询。',
  '女朋友': '亲爱的，终于等到你啦！今天过得怎么样呀？有什么想跟我说的吗~',
  '狗': '汪汪！(摇尾巴) 主人你好呀！想和我一起玩吗？'
}

// 监听消息变化，自动滚动到底部
watch(messages, async () => {
  await nextTick()
  scrollToBottom()
}, {deep: true})

// 监听部分响应变化，自动滚动到底部
watch(partialResponse, async () => {
  await nextTick()
  scrollToBottom()
})

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 角色变更处理
const onRoleChange = (name) => {
  // 清空聊天记录
  messages.value = []
  if (name !== 'custom') {
    // 添加欢迎消息
    messages.value.push({
      role: 'assistant',
      content: welcomeMessages[name] || '你好！很高兴为你服务。'
    })
  }
}

// 保存自定义角色
const saveCustomRole = () => {
  if (!customRoleName.value.trim() || !customRoleDesc.value.trim()) {
    showToast('请填写角色名称和描述')
    return
  }

  // 这里应该调用API保存自定义角色
  console.log('保存角色:', customRoleName.value, customRoleDesc.value)
  showToast('角色保存成功')

  // 清空聊天记录
  messages.value = []
  // 添加自定义角色欢迎消息
  messages.value.push({
    role: 'assistant',
    content: `你好！我是${customRoleName.value}，${customRoleDesc.value}`
  })
}

// 获取当前角色信息
const currentRole = computed(() => {
  if (selectedRole.value !== 'custom') {
    return {
      name: selectedRole.value,
      description: ''
    }
  }
  return {
    name: customRoleName.value,
    description: customRoleDesc.value
  }
})

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  // 添加用户消息到聊天记录
  messages.value.push({
    role: 'user',
    content: inputMessage.value
  })

  const question = inputMessage.value
  inputMessage.value = ''
  isLoading.value = true
  partialResponse.value = ''

  try {
    abortController.value = new AbortController()

    const response = await fetch(_axios.getUri() + '/ai/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('jwt'),
      },
      body: JSON.stringify({
        question,
        role: currentRole.value.name,
        roleDescription: currentRole.value.description
      }),
      signal: abortController.value.signal
    })

    if (!response.ok) {
      showFailToast(`HTTP error! status: ${response.status}`)
      return
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')

    while (true) {
      const {done, value} = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim()
          if (data) {
            partialResponse.value += data
          }
        } else if (line.trim()) {
          partialResponse.value += line.trim()
        }
      }
    }

    // 流式输出完成，将完整响应添加到消息列表
    messages.value.push({
      role: 'assistant',
      content: partialResponse.value
    })

    partialResponse.value = ''
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('请求被取消')
      showToast('请求已取消')
    } else {
      console.log(error)
      showToast(error.message || '发送失败，请重试')
    }
  } finally {
    isLoading.value = false
    abortController.value = null
  }
}

// 组件卸载时取消请求
onUnmounted(() => {
  if (abortController.value) {
    abortController.value.abort()
  }
})

// 初始化欢迎消息
messages.value.push({
  role: 'assistant',
  content: welcomeMessages[selectedRole.value]
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 12px;
}

.role-selector {
  margin-bottom: 16px;
  overflow-x: auto;
  white-space: nowrap;
}

.role-selector ::v-deep .van-radio-group {
  flex-wrap: nowrap;
}

.role-selector ::v-deep .van-radio {
  margin-right: 8px;
}

.custom-role-form {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.message {
  margin-bottom: 12px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.assistant {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 8px 12px;
  border-radius: 8px;
  word-break: break-word;
}

.message.user .message-content {
  background-color: #1989fa;
  color: white;
}

.message.assistant .message-content {
  background-color: #ffffff;
  color: #333;
  border: 1px solid #ebedf0;
}

.input-area {
  display: flex;
  align-items: center;
  gap: 8px;
}

.cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
</style>